﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace EntModApp.EntServices.Data
{
  public static class PagingSettingsExtensions
  {
    public static IQueryable<TEntity> ApplyPagingSettings<TEntity>(this IQueryable<TEntity> query, PagingSettings pagingSettings, out int total)
      where TEntity : class
    {
      if (query == null) throw new ArgumentNullException("query");
      if (pagingSettings == null) pagingSettings = new PagingSettings();
      
      if (pagingSettings.ComputeTotal)
        total = query.Count();
      else 
        total = -1;

      if (pagingSettings.Paginate)
      {
        if (pagingSettings.PageIndex > 0)
          query = query.Skip(pagingSettings.PageIndex * pagingSettings.PageSize);
        query = query.Take(pagingSettings.PageSize);
      }

      return query;
    }
  }
}
